package org.alamoraes.codegen.app.cli;

import java.io.File;
import java.io.PrintStream;
import org.alamoraes.cmdutils.parser.AmCmdLineParser;
import org.alamoraes.codegen.CodeBuilder;
import org.alamoraes.codegen.JsonCodeModelLoader;

/**
 *
 * @author andre
 */
public class Main {
    private static void executeMain(AmCmdLineParser parser) throws Exception {
        CodeBuilder.configureDefaultFactories();

        JsonCodeModelLoader jsonCodeModel = new JsonCodeModelLoader(new File(parser.getValueOf("code-model")));
        CodeBuilder cb = new CodeBuilder(
                new File(parser.getValueOf("o")),
                new File(parser.getValueOf("template")),
                jsonCodeModel.load()
                );

        if (parser.isSet("info")) {
            System.out.println("Target file: " + cb.getTargetFile().getAbsolutePath());
            System.out.println("Template file: " + cb.getTemplateFile().getAbsolutePath());
            System.out.println("User Block Open Tag: " + cb.getBeginUserCodeBlockTag());
            System.out.println("User Block Close Tag: " + cb.getEndUserCodeBlockTag());
            System.out.println("Code Model: " + cb.getCodeModel().toString());
            System.exit(0);
        }

        cb.generate();
        System.out.println("File: " + cb.getTargetFile().getAbsolutePath() + " generated!");

        if (parser.isSet("v"))
            cb.printGenerated(System.out);
    }

    public static void main(String[] args) {
        AmCmdLineParser parser = new AmCmdLineParser();

        parser.addParam("code-model", "Model Definitions", true);
        parser.addParam("template", "Template file", true);
        parser.addParam("o", "Output file", true);
        parser.addSwitch("h", "Help", false);
        parser.addSwitch("v", "Verbose", false);
        parser.addSwitch("info", "Display information about the generation but don't generate files!", false);

        parser.parse(args);

        if (parser.isSet("h") || ! parser.validate()) {
            printUsage(parser, System.out);
            System.exit(0);
        }

        if (parser.isSet("v")) {
            System.out.println("Running code generator at: " + (new File(".")).getAbsolutePath());
        }
        
        try {
            executeMain(parser);
        } catch (Exception ex) {
            System.err.println("Error: " + ex.getMessage());
            if (parser.isSet("v")) {
                ex.printStackTrace(System.err);
            }
        }
    }

    public static void printUsage(AmCmdLineParser parser, PrintStream ps) {
        ps.println("Am Code Gen Tool");
        ps.println("Code generation utility based on Json File Format");
        ps.println("===============================================");
        ps.println("usage: amcodgentool <parameters>");
        ps.println();
        ps.println("Parameters:");
        ps.println("==================");
        parser.printUsage(ps);
    }
}